/**
 * title: useContext
 */
import React, { useContext, useState, createContext } from 'react';

const Context = createContext();

//Context.Consumer
class A1 extends React.Component {
  render() {
    return (
      <div>
        <Context.Consumer>{count => <div>{count}</div>}</Context.Consumer>
      </div>
    );
  }
}

//contextType
class A2 extends React.Component {
  static contextType = Context;
  render() {
    const count = this.context;
    return <div>{count}</div>;
  }
}

//useContext
function A3() {
  const { count, a } = useContext(Context);
  return (
    <div>
      {count}-{a}
    </div>
  );
}

//Context.Provider 载入
function App() {
  const [count, setCount] = useState(0);
  const [a, seta] = useState(0);
  return (
    <div>
      次数：{count}-{a}
      <button onClick={() => setCount(count + 1)}>count+1</button>
      <button onClick={() => seta(a + 1)}>a+1</button>
      <br />
      <Context.Provider value={count}>
        <A1 />
        <A2 />
      </Context.Provider>
      <Context.Provider value={{ count, a }}>
        <A3 />
      </Context.Provider>
    </div>
  );
}

export default App;
